package com.example.springsecurity.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.utils.Base64;
import com.example.springsecurity.utils.ResultBean;
import com.example.springsecurity.utils.redis.RedisCache;
import com.example.springsecurity.utils.uuid.IdUtils;
import com.example.springsecurity.utils.verfycode.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Autowired
    private RedisCache redisCache;

    /**
     * 验证码 redis key
     */
    public static final String CAPTCHA_CODE_KEY = "captcha_codes:";

    /**
     * 验证码有效期（分钟）
     */
    public static final Integer CAPTCHA_EXPIRATION = 2;

    /**
     * 图片base64编码前缀
     */
    public static final String prefix = "data:image/gif;base64,";

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public ResultBean getCode(HttpServletResponse response) throws IOException
    {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        /**
         * 创建键值
         */
        String verifyKey = CAPTCHA_CODE_KEY + uuid;
        /**
         * 存入redis
         */
        redisCache.setCacheObject(verifyKey, verifyCode, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("uuid", uuid);
            /**
             * 生成base64编码只需要即可使用
             */
            jsonObject.put("img", prefix+Base64.encode(stream.toByteArray()));
            return ResultBean.success(jsonObject);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return ResultBean.error(e.getMessage());
        }
        finally
        {
            stream.close();
        }
    }
}